package chapter1.service.impl;

import chapter1.dao.IBaseDao;
import chapter1.domain.entity.BaseEntity;
import chapter1.domain.entity.dto.BaseDto;
import chapter1.domain.entity.vo.BaseVo;
import chapter1.domain.entity.vo.Result;
import chapter1.service.IBaseService;
import java.util.List;

/**
 * 业务层基类-基于容器存储数据
 *
 * @author 郑植航
 * @since 2025/6/1 20:44
 */
abstract class BaseService<Entity extends BaseEntity,Dto extends BaseDto,Vo extends BaseVo,
        Dao extends IBaseDao<Entity>>
        implements IBaseService<Entity,Dto> {

    Dao dao;
    Vo[] temp;

    @Override
    public boolean existById(int id) {
        return dao.existById(id);
    }

    @Override
    public Entity findById(int id) {
        return dao.findById(id);
    }

     abstract Vo convertToVo(Entity entity);


    @Override
    public Result list() {
        List<Vo> list = dao.list().stream().map(this::convertToVo).toList();
        return Result.success("查询成功", list.toArray(temp));
    }


    abstract Entity createEntity(Dto dto);

    @Override
    public Result create(Dto dto) {

        Entity entity= createEntity(dto);
        dao.save(entity);
        return Result.success("创建成功",null);
    }

    abstract void updateEntity(Dto dto,Entity entity);

    @Override
    public Result update(Dto dto, int id) {
        if (!existById(id)) {
            return Result.failure("更新失败，不存在该数据");
        }
        Entity entity= dao.findById(id);

        updateEntity(dto,entity);
        return Result.success("更新成功", null);
    }
}
